/*
 *  Copyright (C) 2025 ameise <ameise.wang@gmail.com> - All Rights Reserved
 *
 *  This file is part of e3utils.
 *
 *  e3utils is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  e3utils is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with e3utils. If not, see <https://www.gnu.org/licenses/>.
 */

package rand

import (
	"strings"
	"time"

	"gitee.com/ameise84/e3utils/uuid"
)

var _gRand *E3Rand

func init() {
	seed := uint64(time.Now().Unix())
	_gRand = NewRand(seed, seed)
}

func Seed(s1 uint64, s2 uint64) {
	_gRand.Seed(s1, s2)
}

func MarshalPCG() ([]byte, error) {
	return _gRand.MarshalPCG()
}

func UnMarshalPCG(bs []byte) error {
	return _gRand.UnMarshalPCG(bs)
}

func R1K() int {
	return _gRand.R1K()
}

func R10K() int {
	return _gRand.R10K()
}

func R100K() int {
	return _gRand.R100K()
}

func IntN(max int) int {
	return _gRand.IntN(max)
}

func Int32N(max int32) int32 {
	return _gRand.Int32N(max)
}

func Int64N(max int64) int64 {
	return _gRand.Int64N(max)
}

func Shuffle(n int, swap func(i, j int)) {
	_gRand.Shuffle(n, swap)
}

func StringN(n int) string {
	sb := strings.Builder{}
	for {
		s := uuid.NewShortV4()
		if len(s) < n {
			sb.WriteString(s)
			n -= len(s)
		} else {
			sb.WriteString(s[:n])
			break
		}
	}
	return sb.String()
}

func ShuffleSlice[T any](s []T) {
	_gRand.Shuffle(len(s), func(i, j int) {
		s[i], s[j] = s[j], s[i]
	})
}

func InSlice[T any](s []T) T {
	size := len(s)
	if size == 0 {
		panic("rand in slice ,slice is empty")
	}
	n := _gRand.IntN(size)
	return s[n]
}

func InSliceN[T any](s []T, n int) []T {
	ShuffleSlice(s)
	return s[:n]
}

func ShuffleSliceWhitRD[T any](rd *E3Rand, s []T) {
	rd.Shuffle(len(s), func(i, j int) {
		s[i], s[j] = s[j], s[i]
	})
}

func InSliceWhitRD[T any](rd *E3Rand, s []T) T {
	size := len(s)
	if size == 0 {
		panic("rand in slice ,slice is empty")
	}
	n := rd.IntN(size)
	return s[n]
}

func InSliceNWhitRD[T any](rd *E3Rand, s []T, n int) []T {
	ShuffleSliceWhitRD(rd, s)
	return s[:n]
}
